package org.agile4j.plugin.gun.xml.new_table;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.agile4j.plugin.gun.helper.GunHelper;
import org.agile4j.plugin.gun.utils.ParserUtil;
import org.agle4j.framework.annotation.Service;
import org.agle4j.framework.utils.CollectionUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 表文件替换
 * 
 * @author hanyx
 * @since
 */
@Service
public class GunTable {

	private static final Logger LOGGER = LoggerFactory.getLogger(GunTable.class);
	private static List<String> list = new ArrayList<>() ;
	static {
		list.add("corp_cd") ;
		list.add("mnt_tlr") ;
		list.add("mnt_brno") ;
		list.add("mnt_date") ;
		list.add("time_stamp") ;
		list.add("rec_stat") ;
	}
	

	public static Map<String, Schema> deplogyTable(File... files) {
		Map<String, Schema> map = new HashMap<>();
		if (files != null && files.length > 0) {
			try {
				for (File innerFile : files) {
					if (innerFile.exists() && innerFile.isFile()) {// 文件对象存
						String xmlFilePath = innerFile.getAbsolutePath();
						Schema sql = ParseTable.getTbsConfig(xmlFilePath);
						map.put(xmlFilePath, sql);
					} else if (innerFile.exists() && innerFile.isDirectory()) {
						Collection<File> filesCollection = FileUtils.listFiles(innerFile, new String[] { "tables.xml" }, true);
						if (CollectionUtils.isNotEmpty(filesCollection)) {
							for (File file : filesCollection) {
								String xmlFilePath = file.getAbsolutePath();
								Schema sql = ParseTable.getTbsConfig(xmlFilePath);
								map.put(xmlFilePath, sql);
							}
						}
					}
				}
			} catch (Exception e) {
				LOGGER.error("deplogy Table failur", e);
				throw new RuntimeException(e);
			}
		}
		return map;
	}
	
	/**
	 * 对默认路径下文件生成目标文件 (替换规则是所有表中存在的GUN_TYPE =0 的字段)
	 * 
	 * @return
	 */
	public boolean createTarFile() {
		return createTarFile(GunHelper.getCreateTarXmlFileUrl());
	}

	
	public boolean createTarFile(String createTarFileUrl) {
		try {
			Map<String, Schema> schemaMap = deplogyTable(new File(createTarFileUrl));
			if (CollectionUtil.isNotEmpty(schemaMap)) {
				for (Map.Entry<String, Schema> schemaEntry : schemaMap.entrySet()) {
					Schema schema = schemaEntry.getValue();
					for (Table table : schema.getTable()) {
						Fields fields = table.getFields() ;
						if (fields != null) {
							List<Field> fieldList = fields.getField() ;
							if (CollectionUtil.isNotEmpty(fieldList)) {
								Iterator<Field> ite = fieldList.iterator() ;
								
								List<String> checkFieldList = new ArrayList<>() ;	// 要添加的字段集合
								checkFieldList.addAll(list) ;
								while (ite.hasNext()) {	// 存在的公共字段重新赋值
									Field field = (Field) ite.next();
									if (isHas(checkFieldList, field.getId())) {
										Iterator<String> fieldite = checkFieldList.iterator() ;
										while (fieldite.hasNext()) {
											String id = (String) fieldite.next();
											if (StringUtils.equalsIgnoreCase(id, field.getId())) { // 表中存在的
												fieldite.remove();
												setFieldValue(field,0);
												LOGGER.debug(schemaEntry.getKey() + " : " + "table:" + table.getId() + " update field: " + field.getId());
											}
										}
									}
								}
								
								// 添加 不存在的公共字段 
								for (String newId : checkFieldList) {
									Field newfield = new Field() ;
									newfield.setId(newId);
									setFieldValue(newfield,1);
									fieldList.add(newfield) ;
									LOGGER.debug(schemaEntry.getKey() + " : " + "table:" + table.getId() + " new field: " + newId);
								}
							}
						}
						
//						Indexes indexs = table.getIndexes() ;
//						if (indexs != null) {
//							List<Index> indexList = indexs.getIndex() ;
//							if (CollectionUtil.isNotEmpty(indexList)) {
//								for (Index index : indexList) {
//									index.getFields() ;
//									for (String id : list) {
//										if (StringUtils.contains(index.getFields(), id)) {
//											String newFields = index.getFields().replace(id, "") ;
//											newFields = StringUtils.deleteWhitespace(newFields) ;
//											newFields = StringUtils.replace(newFields, ",,", ",") ;
//											if (newFields.endsWith(",")) {
//												newFields = newFields.substring(0, newFields.length() -1 ) ;
//											}
//											if (newFields == "") {
//											}
//											LOGGER.debug(schemaEntry.getKey() + " : " + "table:" + table.getId() + " :" + index.getFields() + " ==> " + newFields);
//											index.setFields(newFields);
//										}
//									}
//								}
//							}
//						}
					}
					File file = new File(schemaEntry.getKey());
					String tarFilePath = file.getParent() + File.separator + file.getName(); // 目标文件路径
					ParserUtil.replaceXmlField(tarFilePath, schema);
				}
			}
		} catch (Exception e) {
			LOGGER.error("createTarFile failure", e);
			return false;
		}
		return true;
	}

	private boolean isHas(List<String> list, String id) {
		for (String str : list) {
			if (str.equalsIgnoreCase(id)) {
				return true ;
			}
		}
		return false ;
	}
	
	private void setFieldValue(Field field, int state) {
		if (StringUtils.equalsIgnoreCase("corp_cd", field.getId())) {
			field.setType("varchar");
			field.setMaxLength("4");
			field.setDesc("法人代码");
		}
		if (StringUtils.equalsIgnoreCase("mnt_tlr", field.getId())) {
			field.setType("varchar");
			field.setMaxLength("8");
			field.setDesc("维护柜员");
		}
		if (StringUtils.equalsIgnoreCase("mnt_brno", field.getId())) {
			field.setType("varchar");
			field.setMaxLength("10");
			field.setDesc("维护机构");
		}
		if (StringUtils.equalsIgnoreCase("mnt_date", field.getId())) {
			field.setType("dataString");
			field.setMaxLength("8");
			field.setDesc("维护日期");
		}
		if (StringUtils.equalsIgnoreCase("time_stamp", field.getId())) {
			field.setType("timestamp");
			field.setMaxLength("3");
			field.setDesc("时间戳");
		}
		if (StringUtils.equalsIgnoreCase("rec_stat", field.getId())) {
			field.setType("char");
			field.setMaxLength("1");
			field.setDesc("记录状态");
		}
		
		if(state == 1) { // 只有新添加字段时赋值
			field.setPrimaryKey("false");
			field.setNullable("true");
			field.setUnique("false");
			field.setScale("0");
		}
	}

	public static void main(String[] args) {
		GunTable gunTable = new GunTable() ;
		gunTable.createTarFile() ;
	}
}